/**
 * 
 */
package org.jackysoft.struts2.admin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Namespace;
import org.jackysoft.entity.FieldAccess;
import org.jackysoft.entity.HTMLDocument;
import org.jackysoft.entity.HTMLTemplate;
import org.jackysoft.entity.HibernateWorkflowEntry;
import org.jackysoft.entity.SimpleHtmlElement;
import org.jackysoft.entity.Variable;
import org.jackysoft.opensymphony.workflow.entity.StepDescriptor;
import org.jackysoft.service.FormService;
import org.jackysoft.service.HTMLDocumentService;
import org.jackysoft.service.HTMLTemplateService;
import org.jackysoft.struts2.workflow.AbstractWorkflowAction;
import org.jackysoft.util.WorkflowConstant;
import org.jackysoft.workflow.StepOwner;
import org.jackysoft.workflow.WorkItem;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;



/**
 *  
 *  <dd>根据工作流所在 的步骤,工作流名称,步骤编号,
 *  <dd>显示html页面,,同时根据对个步骤的字段控制
 *  <dd>生成js控制各自段的启用禁用状态
 *  <dd>为了解耦业务和流程，表单采用运行时绑定
 *  @author qujiakang(QQ285799123)
 */
@Controller
@Namespace("/admin/form/show")

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenerateHtmlAction extends AbstractWorkflowAction<WorkItem> {

	
	private static final long serialVersionUID = -2077294210684963020L;
	private FormService formService;
    private HTMLDocumentService htmlDocumentService;
	private HTMLTemplateService tempService;
	
	private Collection<HTMLTemplate> templates;
	private HTMLTemplate template;
	
	private boolean showOnly;
	private String htmlCode;
    private List<SimpleHtmlElement> formElements = new ArrayList<SimpleHtmlElement>();
    
    private boolean auto  = false;
    private boolean withform = true;
	
 	public String execute() throws Exception {	   
 		
 		
		final HibernateWorkflowEntry entry = (HibernateWorkflowEntry) workflowService.findEntry(workflowId);
		final HTMLDocument document = entry.getHtmlDocument();
		if(document==null){
			templates = tempService.gets();		
			return "prerelate";
		}
		actionItem  =workflow.getActionItemById(actionId, workflowId, Collections.EMPTY_MAP);
		Map<Integer,String> nextSteps = Maps.newHashMap();
		for(StepDescriptor step:actionItem.getNextSteps()){
			nextSteps.put(step.getId(), step.getName());
		}
		List<SimpleHtmlElement> htmlValues =  document.getHtmlElement();
		FieldAccess fac = workflowService.getFieldAccess(workflowId, actionItem.getStepId().intValue());
		Variable titleVar = variableService.get(workflowId, WorkflowConstant.FORM_TITLE.toString());
		String title = titleVar==null?"":titleVar.getValue();
		
		htmlCode = formService.generateHtmlForm(actionId,stepId,workflowId,title,nextSteps,document.getData(),htmlValues,fac,showOnly,new HashMap<String,Object>());    	
		return SUCCESS;

	}	
	
 	public String viewform() throws Exception{
 		final HibernateWorkflowEntry entry = (HibernateWorkflowEntry) workflowService.findEntry(workflowId);
		final HTMLDocument document = entry.getHtmlDocument();
		if(document==null){
			htmlCode="此工作流还没有创建表单模版";	
			return "viewform";
		}
 		htmlCode = formService.generateHtmlForm(workflowId, document.getData(), document.getHtmlElement());
 		return "viewform";
 	}
 
	public String prerelate() throws Exception {
		templates = tempService.gets();		
		return "prerelate";
	}
    
    //http://test.qinghua.com:8082/myapps/admin/form/show/generate-html!opentemplate?template.id=402881823293eab401329418c2830003&actionId=4&workflowId=8
    public String opentemplate() throws Exception{
    	actionItem  =workflow.getActionItemById(actionId, workflowId, Collections.EMPTY_MAP);
    	Map<Integer,String> nextSteps = Maps.newHashMap();
		for(StepDescriptor step:actionItem.getNextSteps()){
			nextSteps.put(step.getId(), step.getName());
		}
    	template  = tempService.get(template.getId());  
    	Map<String,Object> transVar = Maps.newHashMap();
    	transVar.put("template", template);
    	FieldAccess fac = workflowService.getFieldAccess(workflowId, actionItem.getStepId().intValue());
    	   	
    	Variable titleVar = variableService.get(workflowId, WorkflowConstant.FORM_TITLE.toString());
		String title = titleVar==null?"":titleVar.getValue();
    	htmlCode = formService.generateHtmlForm(actionId, stepId,workflowId,title,nextSteps,	template.getData(),new ArrayList<SimpleHtmlElement>(),fac,false, transVar);    	
    	return "opentemplate";
    }
    
 
	public String saveform() throws Exception {
		
		actionItem  =workflow.getActionItemById(actionId, workflowId, Collections.EMPTY_MAP);
		setting = entitySettingService.get(workflowId, actionId, stepId);		
		saveFormData(withform);
	    if(setting!=null && setting.getUser()!=null){
			nextOwners = Lists.newArrayList();
			StepOwner so = new StepOwner();
			so.setOwner(setting.getUser());
			so.setStepId(stepId+"");
			nextOwners.add(so);
			auto = true;
			return "toproceed";
		}
	    return "saveform";
	}
	
	private void saveFormData(boolean effect){
		if(!effect)return;
		final HibernateWorkflowEntry entry  = (HibernateWorkflowEntry) workflowService.findEntry(workflowId);
		HTMLDocument formEntry = entry.getHtmlDocument(); 
		if(formEntry==null) {
			formEntry = new HTMLDocument();
			template = tempService.get(template.getId());			
			formEntry.setData(template.getData());
			entry.setHtmlDocument(formEntry);
			workflowService.create(entry);
		}
		//40288182356b7a6301356b7dc9ab0000
		formEntry.getHtmlElement().clear();
		formEntry.getHtmlElement().addAll(formElements);
	    htmlDocumentService.create(formEntry); 
	}
	
	
	
	
	
	public String getHtmlCode() {
		return htmlCode;
	}

	public void setHtmlCode(String htmlCode) {
		this.htmlCode = htmlCode;
	}

		
	@Resource
	public void setFormService(FormService formService) {
		this.formService = formService;
	}

	public boolean isShowOnly() {
		return showOnly;
	}

	public void setShowOnly(boolean showOnly) {
		this.showOnly = showOnly;
	}
  	
	@Resource
	public void setHtmlDocumentService(HTMLDocumentService htmlDocumentService) {
		this.htmlDocumentService = htmlDocumentService;
	}

	public List<SimpleHtmlElement> getFormElements() {
		return formElements;
	}

	public void setFormElements(List<SimpleHtmlElement> formElements) {
		this.formElements = formElements;
	}

	@Resource
	public void setTempService(HTMLTemplateService tempService) {
		this.tempService = tempService;
	}

	public void setTemplates(Collection<HTMLTemplate> templates) {
		this.templates = templates;
	}

	public Collection<HTMLTemplate> getTemplates() {
		return templates;
	}

	public void setTemplate(HTMLTemplate template) {
		this.template = template;
	}

	public HTMLTemplate getTemplate() {
		return template;
	}


	public boolean isAuto() {
		return auto;
	}


	public void setAuto(boolean auto) {
		this.auto = auto;
	}

	public boolean isWithform() {
		return withform;
	}

	public void setWithform(boolean withform) {
		this.withform = withform;
	}	

	
}